/* eslint-disable default-case */
import { message } from 'antd';
import {
  increasePersonnelList,
  AccusearrchDicList,
  getProList,
  getProDetail,
  getFeedback,
  relationxiList,
  relationNumber,
  agreementList,
  invoicList,
  subAgreement,
  fetchSupplierList,
  getTagList,
  getAgreementData,
  // getCustList,
  protocolProductList,
  orderDetails,
  paymentDetailsList,
  cancelSend,
  seeSupplierPeople,
  checkHasTask,
  getBatchId,
  getProgress,
  getAssoDetailData,
  untying,
  orderOnlyData,
} from '@/services/sendIncreasepersonnel';
import * as service from '@/services/socket';

export default {
  state: {
    formFieldsValue: {},
    activeKey: '1',
    expandForm: false,
    pageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    proPageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    custList: [],
    detail: {
      detList: [],
      affixList: [],
    },
    payDetailsData: [],

    proFbList: [],
    proBaseList: {},
    peopleNumber: {},
    addOrEdit: {
      productList: [],
    },
    history: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    servicnftio: [], // 服务类型
    supplierNameList: [], // 供应商名称
    invoicemessage: '',
    dataList: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    }, // 协议列表
    placeExecutionList: [], // 执行地区
    detailsData: {},
    tabList: [
      { itemCode: '1', itemName: '待发单', isHas: false },
      { itemCode: '2', itemName: '已发单', isHas: false },
      { itemCode: '3', itemName: '已接单', isHas: false },
      { itemCode: '4', itemName: '已回单', isHas: false },
      { itemCode: '5', itemName: '问题人员', isHas: false },
      { itemCode: '6', itemName: '已取消', isHas: false },
    ],
    isHasTask: false,
    agreePageData: {
      list: [],
      pagination: {
        current: 1,
        pageSize: 10,
        total: 10,
      },
    },
    selectRowKeys: [],
    selectRows: [],
    batchId: '',
    showProgress: false,
    currentStep: 0,
    progressPercent: 0,
    resultInfo: {
      // 结果数据必传
      batchName: '发单任务', // 任务名称
      taskCount: 0, // 导入数据
      successCount: 0, // 成功数据
      errorCount: 0, // 失败数据
      batchNo: '', // 批次号
      errorUrl: '/nsApi/sendAdd/export/error', // 下载错误信息地址
      errorParams: null, // 下载错误数据参数
    },
  },
  effects: {
    *fetchList({ payload }, { call, put }) {
      const response = yield call(increasePersonnelList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;

      yield put({
        type: 'getList',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });

      if (response.success) {
        yield put({
          type: 'getList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 获取缴纳明细列表
    *getPaymentDetails({ payload }, { call, put }) {
      // console.log(payload);
      const response = yield call(paymentDetailsList, payload);
      if (response.success) {
        // console.log(response);
        yield put({
          type: 'getPayDataList',
          payload: response.data,
        });
      } else {
        message.error('查询失败！');
      }
    },

    // 获取产品列表数据
    *fetchProductList({ payload }, { call, put }) {
      const response = yield call(protocolProductList, payload);
      if (response.success) {
        yield put({
          type: 'getProductList',
          payload: response.data,
        });
      }
    },

    //
    *sendAddper({ payload, callback = () => {} }, { call }) {
      const response = yield call(seeSupplierPeople, payload);
      callback(response);
    },

    // 获取问题人员列表
    *fetchProList({ payload }, { call, put }) {
      const response = yield call(getProList, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getProList',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });
      if (response.success) {
        yield put({
          type: 'getProList',
          payload: {
            data: response.data,
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(`${response.message || '服务端错误！'}`);
      }
    },
    // 问题人员详情
    *feactProDetail({ payload }, { call, put }) {
      const response = yield call(getProDetail, payload);
      yield put({
        type: 'getProDetail',
        payload: {},
      });
      if (response.success) {
        yield put({
          type: 'getProDetail',
          payload: response.data,
        });
      } else {
        message.warning(response.message || '查询失败：服务端未知错误');
      }
    },

    // 详情
    *feactorderDetail({ payload, callback = () => {} }, { call, put }) {
      const response = yield call(orderDetails, payload);

      const sortNumber = (a, b) => a.operLeafType - b.operLeafType;
      if (response.success) {
        if (response.data.execStatusDto && response.data.execStatusDto.leafList) {
          response.data.execStatusDto.leafList = response.data.execStatusDto.leafList.sort(
            sortNumber
          );
        }
        yield put({
          type: 'orderDetails',
          payload: response.data,
        });
      } else {
        yield put({
          type: 'orderDetails',
          payload: {},
        });
      }
      callback(response);
    },

    // 字典查询
    *fetchDicList({ payload }, { call, put }) {
      const response = yield call(AccusearrchDicList, payload);
      if (response.success) {
        yield put({
          type: 'dicList',
          payload: {
            data: response.data,
          },
        });
      }
    },
    // 问题人员反馈
    *proFeedBack({ payload, callback }, { call }) {
      const response = yield call(getFeedback, payload);
      if (response.success) {
        if (callback) {
          callback(response);
        }
      }
    },
    // 问题人员反馈并取消标记
    *cancelProbFlag({ payload, callback = () => {} }, { call }) {
      const response = yield call(getFeedback, payload);
      callback(response);
    },

    // 关联协议：协议列表
    *samllGua({ payload }, { call, put }) {
      const response = yield call(relationxiList, payload);

      const {
        pageArg: { currentPage, pageSize },
      } = payload;

      if (response.success) {
        if (response.data && response.data.pageRecords) {
          response.data.pageRecords.forEach(item => {
            const temp = item;
            if (temp.suppId) {
              temp.supplierNameList = [{ suppId: temp.suppId, name: temp.suppName }];
              temp.defaultValueSupp = [{ suppId: temp.suppId, name: temp.suppName }];
            } else {
              temp.supplierNameList = [];
            } // 每一项供应商下拉
          });
        }
        if (response.data && response.data.pageRecords) {
          response.data.pageRecords.forEach(item => {
            const temp = item;
            temp.isSelect = 1;
            if (temp.suppProtId) {
              temp.supplyDatalist = [
                { suppProtId: temp.suppProtId, suppProtName: temp.suppProtName },
              ];
              temp.defaultValueSuppProt = [
                { suppProtId: temp.suppProtId, suppProtName: temp.suppProtName },
              ];
            } else {
              temp.supplyDatalist = [];
            }
          }); // 每一项供应商协议下拉
        }

        yield put({
          type: 'agreementDataList',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '列表查询失败：服务端未知错误');
        yield put({
          type: 'agreementDataList',
          payload: {
            data: [],
          },
        });
      }
      return response;
    },

    // 关联协议 - 供应商列表
    *fetchSupplyList({ payload, callback }, { call }) {
      const response = yield call(relationxiList, payload);
      if (response.success) {
        if (callback) {
          callback(response);
        }
      }
    },

    // 关联人数
    *associatedNumber({ payload }, { call, put }) {
      const response = yield call(relationNumber, payload);
      if (response.success) {
        yield put({
          type: 'relationPeople',
          payload: response.data,
        });
      }
    },

    // 供应商列表
    *supplierList({ payload }, { call, put, select }) {
      const response = yield call(fetchSupplierList, payload.params);
      const dataList = yield select(state => state.addempsend.dataList);
      const { index } = payload.suppInfo;
      if (response.success) {
        dataList.list[index].supplierNameList = response.data || [];
        if (!response.data.length) {
          dataList.list[index].suppId = '';
        }
        yield put({
          type: 'updateModelData',
          payload: { dataList },
        });
        yield put({
          type: 'getSupplierList',
          payload: response.data,
        });
      } else {
        dataList.list[index].supplierNameList = [];
      }
      return response;
    },

    // 供应商调出供应商协议
    *getAgreementList({ payload }, { call, put }) {
      const parame = {
        areaList: payload.areaList,
        detList: payload.detList,
        recvSuppId: payload.recvSuppId,
        custId: payload.custId,
      };
      const response = yield call(getAgreementData, parame);
      const newResponse = {
        response,
        payload,
      };
      if (response.success) {
        yield put({
          type: 'featchSupplierList',
          payload: newResponse,
        });
      }
      return response;
    },

    // 供应商协议
    *fetchAgreementList({ payload, callback }, { call }) {
      const response = yield call(agreementList, payload);
      if (response.success) {
        if (callback) {
          callback(response);
        }
      }
    },

    // 发单
    *invoicMessage({ payload }, { call, put }) {
      const response = yield call(invoicList, payload);

      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: { batchId: response.data.batchId },
        });
      }
      if (response.success) {
        yield put({
          type: 'initialReset',
          payload: {},
        });
      }
      return response;
    },

    // 创建协议
    *subData({ payload, callback }, { call }) {
      const response = yield call(subAgreement, payload);
      if (callback) {
        callback(response);
      }
    },

    // 查询时看看那个页签下有数据
    *getTagData({ payload }, { call, put, select }) {
      const res = yield call(getTagList, payload);
      const tabList = yield select(state => state.addempsend.tabList);
      let activeKey = yield select(state => state.addempsend.activeKey);
      if (res.success) {
        if (res && res.data.length) {
          const sortNumber = (a, b) => a.tabHdl - b.tabHdl;
          const tabCodeArr = res.data.sort(sortNumber);
          const isHasBadgeCurrentTab = tabCodeArr.some(item => `${item.tabHdl}` === activeKey); // 当前页签有没有查询到
          if (!isHasBadgeCurrentTab) {
            activeKey = `${tabCodeArr[0].tabHdl}`;
          }
          tabList.forEach(items => {
            const temp = items;
            tabCodeArr.sort(sortNumber).forEach(t => {
              if (temp.itemCode === `${t.tabHdl}`) {
                if (res.length === 1) {
                  temp.isHas = false;
                } else {
                  temp.isHas = true;
                }
                if (temp.itemCode === `${t.tabHdl}` && `${t.tabHdl}` === String(activeKey)) {
                  temp.isHas = false;
                }
              }
            });
          });
          yield put({
            type: 'updateModalData',
            payload: { activeKey, tabList },
          });
          const getListParams = {
            ...payload,
            pageArg: {
              currentPage: payload.pageArg.currentPage,
              pageSize: payload.pageArg.pageSize,
            },
          };

          if (activeKey === '5') {
            if (payload.formFieldsValue) {
              yield put({
                type: 'updateModelData',
                payload: {
                  ...payload.formFieldsValue,
                },
              });
            }
            yield put({
              type: 'problempage/getProList',
              payload: {
                ...getListParams,
                busiType: '11',
              },
            });
          } else {
            yield put({
              type: 'fetchList',
              payload: { ...getListParams, busiType: '1', hdlState: activeKey },
            });
          }
          if (activeKey === '1') {
            yield put({
              type: 'associatedNumber',
              payload: { ...getListParams, busiType: '1', hdlState: activeKey },
            });
          }
        } else {
          yield put({
            type: 'getList',
            payload: {
              data: {},
              currentPage: 1,
              pageSize: 10,
              busiType: '1',
            },
          });
          if (activeKey === '5') {
            yield put({
              type: 'problempage/updateProList',
              payload: {
                data: [],
                currentPage: 1,
                pageSize: 10,
              },
            });
          }
        }
      } else {
        message.warning(`${res.message || '服务端错误！'}`);
      }
    },

    *fetchCustList() {
      // const response = yield call(getCustList, { name: payload });
      // yield put({});
    },
    // 取消发单
    *cancelSend({ payload }, { call }) {
      const response = yield call(cancelSend, payload);
      return response;
    },

    // 判断有无任务
    *checkHasTask(_, { call, put }) {
      const response = yield call(checkHasTask);
      if (response.success && response.data) {
        if (response.data.taskCode === 3) {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: true,
              batchId: response.data.batchId,
              taskCode: response.data.taskCode,
            },
          });
        } else {
          yield put({
            type: 'updateModelData',
            payload: {
              isHasTask: false,
            },
          });
        }
      }
    },
    // 获取任务id
    *getBatchId({ payload }, { call, put }) {
      const response = yield call(getBatchId, payload);
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: { batchId: response.data.batchId },
        });
      }
      return response;
    },
    // 获取进度数据
    *getProgress({ payload }, { call, put }) {
      const response = yield call(getProgress, payload);
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: { progressPercent: response.data.successProp },
        });
      }
      return response;
    },

    // 查看客户协议关联情况列表
    *getAssoDetail({ payload }, { call, put }) {
      const response = yield call(getAssoDetailData, payload);
      const {
        pageArg: { currentPage, pageSize },
      } = payload;
      yield put({
        type: 'getAssoDetailDataList',
        payload: {
          data: [],
          currentPage,
          pageSize,
        },
      });

      if (response.success) {
        yield put({
          type: 'getAssoDetailDataList',
          payload: {
            data: response.data || [],
            currentPage,
            pageSize,
          },
        });
      } else {
        message.warning(response.message || '列表查询失败');
        yield put({
          type: 'getAssoDetailDataList',
          payload: {
            data: [],
          },
        });
      }
    },

    // 解绑
    *untyData({ payload }, { call }) {
      const response = yield call(untying, payload);
      return response;
    },

    // 保存并发单
    *orderOnly({ payload }, { call, put }) {
      const response = yield call(orderOnlyData, payload);
      if (response.success && response.data) {
        yield put({
          type: 'updateModelData',
          payload: { batchId: response.data.batchId },
        });
      }
      return response;
    },
    // 上传文件:批量进度:获取batchId后获取进度 isSendType： 1为保存关系并发单 2为仅发单
    *uploadFileWithProgress(
      {
        payload: { isSendType, params },
      },
      { call, put }
    ) {
      const response = yield call(isSendType === 1 ? invoicList : orderOnlyData, params);
      if (response.success) {
        yield put({
          type: 'updateModelData',
          payload: {
            batchId: response.data && response.data.batchId,
            progressPercent: 0,
          },
        });
        yield put({
          type: 'publicdata/fetchSupplyList',
          payload: { name: null, state: 2 },
        });
        if (response.data && response.data.successProp !== 100) {
          yield put({
            type: 'updateModelData',
            payload: {
              showProgress: true,
            },
          });
          yield call(service.socketChannel, {
            type: 'sub',
            data: { to: response.data && (response.data.batchId || response.data), type: 'task' },
          });
        } else {
          yield put({
            type: 'updateBatchTask',
            payload: response.data,
          });
        }
      } else {
        message.warning(`${response.message || '操作失败：服务端错误'}`);
      }
      return response;
    },

    // 匹配唯一batchId
    *matchBatchId({ payload }, { put, select }) {
      const { batchId } = yield select(state => state.addempsend);
      if (batchId === payload.batchId) {
        yield put({
          type: 'updateBatchTask',
          payload,
        });
      }
    },
  },

  reducers: {
    getList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        pageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },

    dicList(
      state,
      {
        payload: { data },
      }
    ) {
      return {
        ...state,
        servicnftio: data,
      };
    },
    // 协议列表
    agreementDataList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        dataList: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },

    // 获取问题人员列表
    getProList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        proPageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },
    // 问题人员详情
    getProDetail(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbkVos || [],
      };
    },
    // 发单增员 - 详情
    orderDetails(state, { payload }) {
      return {
        ...state,
        detailsData: payload,
      };
    },

    // 点击缴纳明细时
    getPayDataList(state, { payload }) {
      return {
        ...state,
        payDetailsData: payload,
      };
    },

    // 关联人数
    relationPeople(state, { payload }) {
      return {
        ...state,
        peopleNumber: payload,
      };
    },
    // 客户名字
    getCustList(state, { payload }) {
      return {
        ...state,
        custList: payload,
      };
    },
    // 供应商名称
    getSupplierList(state, { payload }) {
      return {
        ...state,
        supplierNameList: payload,
      };
    },

    // 添加地区
    addRegion(state, { payload }) {
      return {
        ...state,
        placeExecutionList: payload,
      };
    },

    // 获取产品列表
    getProductList(state, { payload }) {
      return {
        ...state,
        addOrEdit: { ...state.addOrEdit, productList: payload },
      };
    },

    // 文件导出
    exportFile(state, { payload }) {
      return {
        ...state,
        proBaseList: payload,
        proFbList: payload.probFdbkVos,
      };
    },
    // 供应商协议列表
    featchSupplierList(state, { payload }) {
      state.dataList.list.forEach((item, index) => {
        const temp = item;
        if (index === payload.payload.serialNum) {
          temp.supplyDatalist = payload.response.data || [];
          temp.isSelect = 2;
          if (payload.payload.isSupp === 1) {
            temp.suppProtId = '';
            temp.suppId = payload.payload.recvSuppId;
          }
        }
      });
      return {
        ...state,
        dataList: state.dataList,
      };
    },

    // 关联协议清空
    initialReset(state) {
      return {
        ...state,
        supplierNameList: [], // 供应商
      };
    },

    updateModalData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 设置页签状态
    updateTabListQuery(state, { payload }) {
      const { tabList } = state;
      tabList.forEach((item, index) => {
        if (item.itemCode === payload.activeKey) {
          tabList[index].isHas = false;
        }
      });
      return {
        ...state,
        tabList,
        ...payload,
      };
    },

    tableChange(state) {
      const temp = state;
      temp.dataList.list = [];
      return {
        ...state,
      };
    },
    // 更新数据
    updateModelData(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },

    // 查看客户协议关联情况列表
    getAssoDetailDataList(
      state,
      {
        payload: { data, currentPage, pageSize },
      }
    ) {
      const list = Array.isArray(data.pageRecords) ? data.pageRecords : [];
      return {
        ...state,
        agreePageData: {
          list,
          pagination: { total: data.totalCount, current: currentPage, pageSize },
        },
      };
    },

    handlePaginationData(state, { payload }) {
      const { data, current, pageSize } = payload;
      return {
        ...state,
        dataList: {
          list: data,
          pagination: {
            current,
            pageSize,
          },
        },
      };
    },

    // 更新批量任务数据
    updateBatchTask(state, { payload }) {
      let { showProgress, resultInfo } = state;
      showProgress = true;
      if (payload.successProp === 100) {
        resultInfo.errorParams = {
          batchId: payload.batchId,
        };
        resultInfo = { ...resultInfo, ...payload };
      }
      return {
        ...state,
        showProgress,
        progressPercent: payload.successProp,
        resultInfo,
      };
    },
  },

  subscriptions: {
    socket({ dispatch }) {
      return service.listen(action => {
        switch (action.type) {
          case 'task':
            dispatch({
              type: 'matchBatchId',
              payload: action.data,
            });
            // 全局保存
            dispatch({
              type: 'publicdata/updateBatchTaskData',
              payload: action.data,
            });
            break;
        }
      });
    },
  },
};
